package com.example.lockLearning;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Lock3 {

    private final Lock lock = new ReentrantLock();

    /**
     * 如果在规定时间内无法获取锁，可以放弃或执行其他任务。
     * 1. `tryLock(1, TimeUnit.SECONDS)` 会在 1 秒内尝试获取锁。
     * 2. 如果超过 1 秒仍未获取到锁，返回 `false`。
     */
    public void timedIncrement() {
        try {
            if (lock.tryLock(1, TimeUnit.SECONDS)) {
                try {
                    for (int i = 0; i < 5; i++) {
                        System.out.println(Thread.currentThread().getName() + " got lock " + i);
                    }
                    Thread.sleep(2000);
                } finally {
                    lock.unlock();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + " failed to get lock ");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {

        Lock3 lock3 = new Lock3();

        Thread t1 = new Thread(lock3::timedIncrement);
        Thread t2 = new Thread(lock3::timedIncrement);

        t1.start();
        t2.start();

    }
}
